/*
 * File: VmsMetrics.java Author: Fating <xingon@163.com>
 * 
 * Created on 2014年12月19日下午7:35:01
 * 
 * Copyright (c) 2014, www.vip.com All Rights Reserved.
 */
package com.tc.vms.metric;

import com.tc.vms.consumer.VmsConsumerMetrics;
import com.tc.vms.iface.VmsMetaData;
import com.tc.vms.producer.ChannelMetaData;
import com.tc.vms.producer.VmsProducerMetrics;
import com.tc.vms.utils.Utils;

import java.util.HashMap;

public class VmsMetricsManager {
    private final HashMap<String, VmsMetricsGroup> stats = new HashMap<String, VmsMetricsGroup>();
    private final Object createLock = new Object();

    public <T extends VmsMetricsGroup> T getVmsMetrics(VmsMetaData vmsMetaData) {
        String metricsId = genMetricsId(vmsMetaData);
        if (!stats.containsKey(metricsId)) {
            VmsMetricsGroup vmsMetricsGroup = null;
            synchronized (createLock) {
                if (vmsMetaData instanceof ChannelMetaData) {
                    vmsMetricsGroup = new VmsProducerMetrics(metricsId);
                } else {
                    vmsMetricsGroup = new VmsConsumerMetrics(metricsId);
                }
                stats.put(metricsId, vmsMetricsGroup);
            }
        }
        return (T) stats.get(metricsId);
    }

    public void removeVmsMetrics(VmsMetaData vmsMetaData) {
        String metricsId = genMetricsId(vmsMetaData);
        if (stats.containsKey(metricsId)) {
            synchronized (createLock) {
                VmsMetricsGroup vmsMetricsGroup = stats.remove(metricsId);
                if (vmsMetricsGroup != null) {
                    if (vmsMetaData instanceof ChannelMetaData) {
                        vmsMetricsGroup.removeAllProducerMetrics(metricsId);
                    } else {
                        vmsMetricsGroup.removeAllConsumerMetrics(metricsId);
                    }
                }
            }
        }
    }

    public HashMap<String, VmsMetricsGroup> getStats() {
        return stats;
    }

    private String genMetricsId(VmsMetaData vmsMetaData) {
        String clientId = vmsMetaData.getOrigClientId();
        String channelOrQueueName = vmsMetaData.getZnodeName();
        return Utils.mkString("-", clientId, channelOrQueueName);
    }

}
